#pragma once
#include <iostream>
#include <string>
#include <queue>
#include <pthread.h>

const int defaultcap = 5;

template <typename T>
class BlockQueue
{
private:
    bool IsFull() { return _q.size() >= _cap; }
    bool IsEmpty() { return _q.size() == 0; }

public:
    BlockQueue(int cap = defaultcap)
        : _cap(cap), _csleep_num(0), _psleep_num(0)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_full_cond, nullptr);
        pthread_cond_init(&_empty_cond, nullptr);
    }

    void Enqueue(const T &in)
    {

        pthread_mutex_lock(&_mutex);

        while (IsFull())
        {
            _psleep_num++;
            std::cout << "生产者，进入休眠了: _psleep_num" << _psleep_num << std::endl;
            pthread_cond_wait(&_full_cond, &_mutex);
            _psleep_num--;
        }
        _q.push(in);

        if (_csleep_num > 0)
        {
            pthread_cond_signal(&_empty_cond);
            std::cout << "唤醒消费者..." << std::endl;
        }

        // pthread_cond_signal(&_empty_cond);
        pthread_mutex_unlock(&_mutex);
    }

    T Pop()
    {
        pthread_mutex_lock(&_mutex);

        while (IsEmpty())
        {
            _csleep_num++;
            std::cout << "消费者,进入休眠,_csleep_num: " << _csleep_num << std::endl;
            _csleep_num--;
        }

        T data = _q.front();
        _q.pop();

        if (_psleep_num > 0)
        {
            pthread_cond_signal(&_full_cond);
            std::cout << "唤醒生产者..." << std::endl;
        }
        pthread_mutex_unlock(&_mutex);
        return data;
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_full_cond);
        pthread_cond_destroy(&_empty_cond);
    }

private:
    int _csleep_num; // 消费者休眠数量
    int _psleep_num; // 生产者消费数量

    pthread_cond_t _full_cond;
    pthread_cond_t _empty_cond;
    pthread_mutex_t _mutex;

    int _cap;         // 队列大小
    std::queue<T> _q; // 任务队列
};